package com.thinkingstar.iads.projectcenter.serviceImpl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.QueryResult;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.adaptor.convertor.StringParamConvertor;

import com.thinkingstar.iads.common.jsonUtils.AjaxResult;
import com.thinkingstar.iads.datacenter.entity.DcEquipmentBudget;
import com.thinkingstar.iads.datacenter.entity.DcEquipmentChildrenType;
import com.thinkingstar.iads.datacenter.entity.DcProjectDesignCell;
import com.thinkingstar.iads.datacenter.entity.common.dao.CommonDao;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcFormField;
import com.thinkingstar.iads.datacenter.entity.dao.DaoEquipmentBudget;
import com.thinkingstar.iads.projectcenter.entity.PcProjectEquipmentEquip;
import com.thinkingstar.iads.projectcenter.entity.PcProjectEquipmentEquipInfo;
import com.thinkingstar.iads.projectcenter.entity.PcProjectInfo;
import com.thinkingstar.iads.projectcenter.entity.dao.DaoPcEquipmentEquip;
import com.thinkingstar.iads.projectcenter.entity.dao.DaoPcProjectData;
import com.thinkingstar.iads.projectcenter.entity.dao.DaoPcProjectEquipmentEquipInfo;

import net.sf.ehcache.hibernate.nonstop.NonstopAccessStrategyFactory;

//设备概算计算规则service
@IocBean
public class EquipmentBudgetServiceImpl{
	
	@Inject
	private DaoEquipmentBudget daoEquipmentBudget;
	
	@Inject 
	private CommonDao commonDao;

	@Inject
	private DaoDcFormField daoDcFormField;
	
	@Inject
	private DaoPcProjectData daoPcProjectData;
	
	@Inject
	private DaoPcEquipmentEquip daoPcEquipmentEquip;
	
	@Inject
	private DaoPcProjectEquipmentEquipInfo daoPcProjectEquipmentEquipInfo;
	
	private List <NutMap> list = new ArrayList<>();
	
	private BigDecimal jzgcf_price = new BigDecimal(0); //建筑工程费
	
	private BigDecimal azgcf_price = new BigDecimal(0); //安装工程费
	
	private BigDecimal sbgzf_price = new BigDecimal(0); //设备购置费
	
	
	/**
	 * 根据项目id查找设计概算
	 * */
	public NutMap getEquipmentBudgetTable(NutMap param) {
		String project_id = param.getString("project_id");
		PcProjectInfo project_info = daoPcProjectData.fetch(project_id);
		DcEquipmentBudget result = daoEquipmentBudget.findEquipmentBudgetByPhaseIdAndMajorIdAndContentId(project_info);
		if(result != null){
			String equipment_budget_code = result.getEquipment_budget_table_code();
			String table_name = new StringBuilder("dc_sbgs_").append(equipment_budget_code).toString();
			param.put("table_name", table_name);
			QueryResult data_list = commonDao.findDesignCellDataByTableName(param);
			//结构化数据表单表头
			List <NutMap> field_list = daoDcFormField.queryColumnList(table_name);
			NutMap data_map = new NutMap();
			data_map.put("title_list", field_list);
			data_map.put("data_list", data_list);
			data_map.put("table_name", table_name);
			return data_map;
		}
		return null;
	}
	
	//根据备注获取字段名称
	public String getFieldNameByComment(String field_comment){
		//表头
		for(NutMap data : list){
			String data_field_comment = data.getString("field_comment");
			if(field_comment.trim().equals(data_field_comment.trim())){
				return data.getString("field_name");
			}
		}
		return null;
	}
	
	//获取表头
	public void initColumnList(String table_name){
		list = daoDcFormField.queryColumnList(table_name);
	}
	
	//写入设备计算规则
	public NutMap addData(String[] strings){
		NutMap nutMap = new NutMap(getFieldNameByComment("单价编号"),strings[0])
				.addv(getFieldNameByComment("工作项目或费用名称"), strings[1])
				.addv(getFieldNameByComment("单位"), strings[2])
				.addv(getFieldNameByComment("数量"), strings[3])
				.addv(getFieldNameByComment("单价"), strings[4])
				.addv(getFieldNameByComment("合价"), strings[5]);
		return nutMap;
	}
	
	//生成设备概算总表
	public AjaxResult equipmentCaculate(String project_id , String table_name){
		try {
			//1.设备购置费计算
			List <NutMap> sbgzf = equipmentSumPriceCaculate(project_id,table_name);
			//2.建筑工程费
			List <NutMap> jzgcf = equipmentJzgcfPriceCaculate(project_id,table_name);
			//3.安装工程费
			List <NutMap> azgcf = equipmentAzgcfCaculate(project_id , table_name);
			//总额
			String [] sum_price = new String[]{"","总额","","","",jzgcf_price.add(azgcf_price.add(sbgzf_price)).toString()};
			List <NutMap> data_list = new ArrayList<>();
			data_list.add(addData(sum_price));
			data_list.addAll(jzgcf);
			data_list.addAll(azgcf);
			data_list.addAll(sbgzf);
			//先清空历史记录
			commonDao.delRecord(table_name, project_id);
			commonDao.addDataOfNumber(table_name, data_list, project_id);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("计算过程中出现异常!");
		}
		return AjaxResult.success("计算完成!");
	}
	
	
	//安装工程费用计算
	public List <NutMap> equipmentAzgcfCaculate(String project_id , String table_name){
		List <NutMap> equipmentAzgcfPrice = new ArrayList<>();
		BigDecimal equipment_sum_price = getEquipmentSumPrice(project_id,table_name);//设备合价
		String rgfbl = getRgfbl("人工费",project_id,table_name);
		BigDecimal rgf_price = equipment_sum_price.multiply(new BigDecimal(rgfbl).divide(new BigDecimal(100)));
		rgf_price = new BigDecimal(getTwoDecimals(rgf_price.toString()));
		String [] rgf_price_data = new String[]{"SH","人工费","元",equipment_sum_price.toString(),rgfbl,rgf_price.toString()};
		equipmentAzgcfPrice.add(addData(rgf_price_data));
		String flfbl = getRgfbl("辅料费", project_id, table_name);
		BigDecimal flf_price = equipment_sum_price.multiply(new BigDecimal(flfbl).divide(new BigDecimal(100)));
		flf_price = new BigDecimal(getTwoDecimals(flf_price.toString()));
		String [] flf_price_data = new String[]{"SH","辅料费","元",equipment_sum_price.toString(),flfbl,flf_price.toString()};
		equipmentAzgcfPrice.add(addData(flf_price_data));
		String jxfbl = getRgfbl("机械费", project_id, table_name);
		BigDecimal jxf_price = equipment_sum_price.multiply(new BigDecimal(jxfbl).divide(new BigDecimal(100)));
		jxf_price = new BigDecimal(getTwoDecimals(jxf_price.toString()));
		String [] jxf_price_data = new String[]{"SH","机械费","元",equipment_sum_price.toString(),jxfbl,jxf_price.toString()};
		equipmentAzgcfPrice.add(addData(jxf_price_data));
		BigDecimal azgcf_price = rgf_price.add(flf_price.add(jxf_price));
		String [] azgcf_price_data = new String[]{"","安装工程费","处","","",azgcf_price.toString()};
		equipmentAzgcfPrice.add(0, addData(azgcf_price_data));
		this.azgcf_price = azgcf_price;
		return equipmentAzgcfPrice;
	}
	
	
	//建筑工程费计算
	public List<NutMap> equipmentJzgcfPriceCaculate(String project_id , String table_name){
		List <NutMap> equipmentJzgcfCaculate = new ArrayList<>();
		String [] strings = getGygdPriceNum(project_id,table_name);
		String price = strings[0];
		String number = strings[1];
		BigDecimal combined_price = new BigDecimal(price).multiply(new BigDecimal(number));
		String [] equipmentJzgcf = new String[]{"","建筑工程费","处","","",combined_price.toString()};
		equipmentJzgcfCaculate.add(addData(equipmentJzgcf));
		String [] equipmentSwgygd = new String[]{"","室外工艺管道","处","","",combined_price.toString()};
		equipmentJzgcfCaculate.add(addData(equipmentSwgygd));
		String [] equipmentGygd = new String[]{"SH","工艺管道","元",number,price,combined_price.toString()};
		equipmentJzgcfCaculate.add(addData(equipmentGygd));
		this.jzgcf_price = combined_price;
		return equipmentJzgcfCaculate;
	}
	
	//去除设备合价
	public BigDecimal getEquipmentSumPrice(String project_id , String table_name){
		//单个设备计算
		List <NutMap> equipmntPriceCaculate = equipmntPriceCaculate(project_id,table_name);
		//设备原价
		BigDecimal sum_price = new BigDecimal(0);
		for(NutMap equipment_price : equipmntPriceCaculate){
			String combined_price = equipment_price.getString(getFieldNameByComment("合价"));
			if(StringUtils.isNotBlank(combined_price)){
				sum_price = sum_price.add(new BigDecimal(combined_price));
			}
		}
		return sum_price;
	}
	
	//设备税金,运杂费相关计算
	public List <NutMap> equipmentSumPriceCaculate(String project_id , String table_name){
		//单个设备计算
		List <NutMap> equipmntPriceCaculate = equipmntPriceCaculate(project_id,table_name);
		BigDecimal sum_price = getEquipmentSumPrice(project_id,table_name);//设备合价
		//以上合计
		String [] equipment_sum_price = new String[]{"","以上合计","元","","",sum_price.toString()};
		equipmntPriceCaculate.add(addData(equipment_sum_price));
		//设备原价
		String [] equipment_original_price = new String[]{"","设备原价","元","","",sum_price.toString()};
		equipmntPriceCaculate.add(addData(equipment_original_price));
		//设备运杂费(若数据库中已有设备运杂费比例,按库中数据为准,否则按默认值6.5个百分点)
		String sbyzfbl = getYzfbl(project_id,table_name);
		BigDecimal sbyzf_price = sum_price.multiply(new BigDecimal(sbyzfbl).divide(new BigDecimal(100)));
		//保留两位小数   
		sbyzf_price = new BigDecimal(getTwoDecimals(sbyzf_price.toString()));
		String [] equipment_sbyzf_price = new String[]{"","设备运杂费","%",sum_price.toString(),sbyzfbl,sbyzf_price.toString()};
		equipmntPriceCaculate.add(addData(equipment_sbyzf_price));
		//设备税金费(设备原价+设备运杂费)/比例
		String sbsjbl = getSbsjbl(project_id,table_name);
		BigDecimal sbsjf_sum_price = sum_price.add(sbyzf_price); //要扣除的设备税金总价
		BigDecimal sbsjf_price = sbsjf_sum_price.multiply(new BigDecimal(sbsjbl).divide(new BigDecimal(100))); //设备税金费用
		sbsjf_price = new BigDecimal(getTwoDecimals(sbsjf_price.toString()));
		String [] equipment_sbsjf_price = new String[]{"","设备税金","%",sbsjf_sum_price.toString(),sbsjbl,sbsjf_price.toString()};
		equipmntPriceCaculate.add(addData(equipment_sbsjf_price));
		//单项预估价值(设备原价+设备运杂费+设备税金)
		BigDecimal dxygjz_price = sum_price.add(sbyzf_price.add(sbsjf_price));
		this.sbgzf_price = dxygjz_price;
		String [] equipment_dxygjz_price = new String[]{"","单项预估价值","元","","",dxygjz_price.toString()};
		equipmntPriceCaculate.add(addData(equipment_dxygjz_price));
		String [] equipment_sbgzf_price = new String[]{"","设备购置费","处","","",dxygjz_price.toString()};
		equipmntPriceCaculate.add(0, addData(equipment_sbgzf_price));
		return equipmntPriceCaculate;
	}
	
	
	//设备库各个设备计算
	public List<NutMap> equipmntPriceCaculate(String project_id , String table_name){
		initColumnList(table_name);
		List<NutMap> list = new ArrayList<>();
		NutMap data_map = null;
		//根据取用的设备库计算这个项目的设备概算信息
		List<PcProjectEquipmentEquip> equipment_equip_list = daoPcEquipmentEquip.findEquipmentEquipByProjectId(project_id);
		if(!equipment_equip_list.isEmpty()){
			for(PcProjectEquipmentEquip pcProjectEquipmentEquip : equipment_equip_list){
				String [] equipment_equips = new String[]{"",pcProjectEquipmentEquip.getEquipment_equip_name(),"","","",""};
				list.add(addData(equipment_equips));
				//2.设备类型信息
				List <PcProjectEquipmentEquipInfo> equipment_equip_info_list = daoPcProjectEquipmentEquipInfo.findEquipmentEquipInfoByEquipId(pcProjectEquipmentEquip.getId());
				Set <DcEquipmentChildrenType> equipment_type_list = getEquipmentTypeByEquipmentList(equipment_equip_info_list);
				for(DcEquipmentChildrenType dcEquipmentChildrenType : equipment_type_list){
					String [] equipment_type = new String[]{"",dcEquipmentChildrenType.getEquipment_children_type_name(),"","","",""};
					list.add(addData(equipment_type));
					//3.设备库信息
					List <PcProjectEquipmentEquipInfo> equipment_info_list = daoPcProjectEquipmentEquipInfo.findEquipmentEquipInfoByEquipIdAndEquipmentTypeId(pcProjectEquipmentEquip.getId(),dcEquipmentChildrenType.getId());
					if(!equipment_info_list.isEmpty()){
						for(PcProjectEquipmentEquipInfo pcProjectEquipmentEquipInfo : equipment_info_list){
							String [] equipment_nums = new String[]{"SF",pcProjectEquipmentEquipInfo.getEquipment_name(),
									"",pcProjectEquipmentEquipInfo.getEquipment_num(),
									pcProjectEquipmentEquipInfo.getEquipment_price(),getCombinedPrice(pcProjectEquipmentEquipInfo.getEquipment_num(),pcProjectEquipmentEquipInfo.getEquipment_price())};
							list.add(addData(equipment_nums));
						}
					}
				}
			}
		}
		return list;
	}
	
	//查询工艺管道的单价以及数量
	public String[] getGygdPriceNum(String project_id , String table_name){
		String [] strings = new String[2]; //工艺管道单价以及数量
		Boolean is_exist = false;
		QueryResult queryResult = commonDao.findDataByTableName(new NutMap("table_name",table_name).addv("project_id", project_id));
		if(queryResult != null){
			List <NutMap> result_list =  (List<NutMap>) queryResult.getList();
			for(NutMap result_map : result_list){
				String key = result_map.getString(getFieldNameByComment("工作项目或费用名称"));
				String price = result_map.getString(getFieldNameByComment("单价"));
				String number = result_map.getString(getFieldNameByComment("数量"));
				if(StringUtils.isNotBlank(key) && "工艺管道".equals(key.trim()) && StringUtils.isNotBlank(price) && StringUtils.isNotBlank(number)){
					strings[0] = price;
					strings[1] = number;
					is_exist = true;
					break;
				}
			}
		}
		if(is_exist){
			return strings;
		}
		return new String[]{"300","5000"};
	}
	
	//查询设备运杂费比例
	public String getYzfbl(String project_id , String table_name){
		String yzfbk = ""; //设备运杂费比例(百分比表示)
		Boolean is_exist = false;
		QueryResult queryResult = commonDao.findDataByTableName(new NutMap("table_name",table_name).addv("project_id", project_id));
		if(queryResult != null){
			List <NutMap> result_list =  (List<NutMap>) queryResult.getList();
			for(NutMap result_map : result_list){
				String key = result_map.getString(getFieldNameByComment("工作项目或费用名称"));
				String value = result_map.getString(getFieldNameByComment("单价"));
				if(StringUtils.isNotBlank(key) && "设备运杂费".equals(key.trim()) && StringUtils.isNotBlank(value)){
					yzfbk = value;
					is_exist = true;
					break;
				}
			}
		}
		if(is_exist){
			return yzfbk;
		}
		return new String("6.5"); //默认6.5个百分点
	}
	
	//查询人工费,辅料费,
	public String getRgfbl(String fy_type  , String project_id , String table_name){
		String fybl = "";
		Boolean is_exist = false;
		QueryResult queryResult = commonDao.findDataByTableName(new NutMap("table_name",table_name).addv("project_id", project_id));
		if(queryResult != null){
			List <NutMap> result_list =  (List<NutMap>) queryResult.getList();
			for(NutMap result_map : result_list){
				String key = result_map.getString(getFieldNameByComment("工作项目或费用名称"));
				String value = result_map.getString(getFieldNameByComment("单价"));
				if(StringUtils.isNotBlank(key) && fy_type.trim().equals(key.trim()) && StringUtils.isNotBlank(value)){
					fybl = value;
					is_exist = true;
					break;
				}
			}
		}
		if(is_exist){
			return fybl;
		}
		return new String("2");//2个百分点
	}
	
	
	//查询设备税金
	public String getSbsjbl(String project_id , String table_name){
		String sbsjbl = ""; //设备税金比例(百分比表示)
		Boolean is_exist = false;
		QueryResult queryResult = commonDao.findDataByTableName(new NutMap("table_name",table_name).addv("project_id", project_id));
		if(queryResult != null){
			List <NutMap> result_list =  (List<NutMap>) queryResult.getList();
			for(NutMap result_map : result_list){
				String key = result_map.getString(getFieldNameByComment("工作项目或费用名称"));
				String value = result_map.getString(getFieldNameByComment("单价"));
				if(StringUtils.isNotBlank(key) && "设备税金".equals(key.trim()) && StringUtils.isNotBlank(value)){
					sbsjbl = value;
					is_exist = true;
					break;
				}
			}
		}
		if(is_exist){
			return sbsjbl;
		}
		return new String("11"); //默认11个百分点
	}
	
	
	//根据单价以及数量计算合价
	public String getCombinedPrice(String num , String price){
		if(StringUtils.isBlank(num) || StringUtils.isBlank(price)){
			num = "0";
			price = "0";
		}
		Double price_double = Double.valueOf(price);
		BigDecimal big_price = new BigDecimal(price_double);
		BigDecimal num_price = new BigDecimal(num);
		String result = num_price.multiply(big_price).toString();
		return getTwoDecimals(result);
	}
	
	//截取到小数点后两位小数
	public String getTwoDecimals(String result){
		if(result.indexOf(".") > -1 ){
			if(result.length() - result.lastIndexOf(".") > 3){
				return result.substring(0,result.indexOf(".")+3);
			}
		}
		return result;
	}
	
	//根据设备库列表查询设备类型
	public Set<DcEquipmentChildrenType> getEquipmentTypeByEquipmentList(List <PcProjectEquipmentEquipInfo> equipment_equip_info_list){
		Set<DcEquipmentChildrenType> equipment_type_list = new HashSet<>();
		for(PcProjectEquipmentEquipInfo pcProjectEquipmentEquipInfo : equipment_equip_info_list){
			DcEquipmentChildrenType dc = daoPcProjectEquipmentEquipInfo.getEquipmentTypeByEquipment(pcProjectEquipmentEquipInfo);
			equipment_type_list.add(dc);
		}
		return equipment_type_list;
	}
	
	public static void main(String[] args) {
		List <String> link_list = new ArrayList();
		link_list.add("1");
		link_list.add("2");
		link_list.add(0, "0");
		for(String string : link_list){
			System.out.println(string);
		}
	}
	
	
}
